﻿<template>
    <el-input v-model="currentValue"
              :placeholder="$t(myPlaceholder)"
              :disabled="disabled"
              :type="type"
              :rows="rows"
              :readonly="readonly"
              :autocomplete="autocomplete"
              :style="style"
              :size="size"
              ref="input"
              :autosize="autosizeVal"
              :minlength="minlength"
              :maxlength="maxlength"
              show-word-limit
              @change="change"
              @blur="blur"
              @focus="focus">
             <template v-if="slotType" :slot="slotType" v-html="slotHtml"></template>
         </el-input>
</template>

<script>
export default {
  components: {},
  data () {
    return {
      currentValue: '',
      autosizeVal: {}
    }
  },
  props: {
    value: [String, Number],
    slotType: String,
    slotHtml: String,
    size: {
      type: String,
      default: ''
    },
    minlength: Number,
    maxlength: Number,
    autocomplete: String,
    placeholder: String,
    disabled: Boolean,
    readonly: Boolean,
    auto: Boolean,
    width: [String],
    type: {
      type: String,
      default: 'text'
    },
    autosize: Object,
    slots: {
      type: Object,
      default () {
        return {
          input: []
        }
      }
    },
    rows: {
      type: Number,
      default: 10
    }
  },
  computed: {
    myPlaceholder () {
      return this.placeholder || (this.auto && '自动生成' || '')
    },
    style () {
      let styleSheet = []

      if (this.width) {
        styleSheet.push(`width:${this.width}`)
      }

      return styleSheet.join(';')
    }
  },
  watch: {
    value: {
      immediate: true,
      handler (newVal) {
        // 如果启用了自动生成值，并且赋值内容是自动生成，则不更新
        // if (newVal == '$auto$' && this.auto && this.currentValue == '') {
        //     return;
        // }

        this.currentValue = newVal
      }
    },
    currentValue: {
      immediate: true,
      handler (newVal) {
        newVal = this.submitValue(newVal)

        if (this.value != newVal) {
          this.$emit('input', newVal)
        }
      }
    }
  },
  methods: {
    // 转换提交的值
    submitValue (newVal) {
      newVal = (newVal || '').toString().trim()

      if (newVal.trim() == '' && this.auto) {
        newVal = '$auto$'
      }

      return newVal
    },
    // 改变值事件
    change (newVal) {
      this.$emit('change', this.submitValue(newVal))
    },
    // 失去焦点事件
    blur (e) {
      this.$emit('blur', e)
    },
    // 获得焦点事件
    focus (e) {
      this.$emit('focus', e)
    },
    click (e) {
      e.stopPropagation()
    }
  },
  created () {
    if (this.type === 'textarea') {
      let auto = {
        minRows: 2,
        maxRows: 6
      }
      this.autosizeVal = this.autosize || auto
    }
    return

    this.$emit('created', {
      focus: () => {
        this.$refs.input.focus()
      }
    })
  }
}
</script>
